package com.song.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.song.mapper.UserMapper;
import com.song.pojo.Teacher;
import com.song.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/test")
    public void test(){
        System.out.println("进来了");
    }

    @GetMapping("/query")
    public List<User> queryUserList(){
        List<User> users = userMapper.queryUserList();
        for (User user : users) {
            System.out.println(user);
        }
        return users;
    }

    /**
     *  批量下载  http://localhost:9999/download
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        List<User> list = userMapper.queryUserList();
        String fileName = "学生表.xlsx";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentType("application/vnd.ms-excel");
        EasyExcel.write(response.getOutputStream(),User.class)
                .sheet("test1")
                .doWrite(list);
        System.out.println("response=====》"+response);
    }


    /**
     *  多sheet页   http://localhost:9999/downloadSheets
     */
    @GetMapping("/downloadSheets")
    public void downloadSheets(HttpServletResponse response) throws IOException {
        List<User> userList = userMapper.queryUserList();
        List<Teacher> orderList = userMapper.queryTeacherList();

        String fileName = "订单表.xlsx";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentType("application/vnd.ms-excel");

        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = EasyExcel.write(out).build();

        WriteSheet userSheet = EasyExcel.writerSheet(0, "学生表").head(User.class).build();
        writer.write(userList, userSheet);

        WriteSheet orderSheet = EasyExcel.writerSheet(1, "教师表").head(Teacher.class).build();
        writer.write(orderList, orderSheet);

        writer.finish();
    }

}
